package org.example.demo1.servlets.functionPage;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
import org.apache.ibatis.session.SqlSession;
import org.example.demo1.DAO.NovelDao;
import org.example.demo1.Entity.Novel;
import org.example.demo1.Entity.User;
import org.example.demo1.utils.FileUploadOss;
import org.example.demo1.utils.MybatisUtils;
import org.example.demo1.service.Authorworkservice;
import org.example.demo1.service.servicelmpl.Authorworkservicelmpl;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

@WebServlet("/API/Author/*")
@MultipartConfig  // 添加文件上传支持
public class AuthorServlet extends HttpServlet {
    
    private Authorworkservice authorworkservice = new Authorworkservicelmpl();
    private static final String TEMP_DIR = "D:\\tools\\web\\demo1\\src\\main\\webapp\\temp";
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        
        if (user == null) {
            Map<String, Object> result = new HashMap<>();
            result.put("code", 401);
            result.put("msg", "用户未登录");
            
            Gson gson = new Gson();
            out.write(gson.toJson(result));
            return;
        }
        
        String pathInfo = req.getPathInfo();
        
        try {
            if (pathInfo != null && pathInfo.equals("/statistics")) {
                // 获取作者统计数据
                Map<String, Object> statistics = authorworkservice.getAuthorStatistics(user.getUser_id());
                
                Map<String, Object> result = new HashMap<>();
                result.put("code", 200);
                result.put("msg", "获取统计数据成功");
                result.put("data", statistics);
                
                Gson gson = new Gson();
                out.write(gson.toJson(result));
                
            } else if (pathInfo != null && pathInfo.equals("/novels")) {
                // 获取作者作品列表
                String pageNumStr = req.getParameter("pageNum");
                String pageSizeStr = req.getParameter("pageSize");
                String status = req.getParameter("status");
                String keyword = req.getParameter("keyword");
                
                int pageNum = pageNumStr != null ? Integer.parseInt(pageNumStr) : 1;
                int pageSize = pageSizeStr != null ? Integer.parseInt(pageSizeStr) : 10;
                
                Map<String, Object> novelsData = authorworkservice.getAuthorNovels(
                    user.getUser_id(), pageNum, pageSize, status, keyword);
                
                Map<String, Object> result = new HashMap<>();
                result.put("code", 200);
                result.put("msg", "获取作品列表成功");
                result.put("total", novelsData.get("total"));
                result.put("rows", novelsData.get("rows"));
                result.put("pageNum", novelsData.get("pageNum"));
                result.put("pageSize", novelsData.get("pageSize"));
                
                Gson gson = new Gson();
                out.write(gson.toJson(result));
                
            } else {
                Map<String, Object> result = new HashMap<>();
                result.put("code", 404);
                result.put("msg", "请求路径不存在");
                
                Gson gson = new Gson();
                out.write(gson.toJson(result));
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("msg", "服务器内部错误: " + e.getMessage());
            
            Gson gson = new Gson();
            out.write(gson.toJson(result));
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        
        if (user == null) {
            Map<String, Object> result = new HashMap<>();
            result.put("code", 401);
            result.put("msg", "用户未登录");
            
            Gson gson = new Gson();
            out.write(gson.toJson(result));
            return;
        }
        
        String pathInfo = req.getPathInfo();
        
        try {
            if (pathInfo != null && pathInfo.equals("/create")) {
                String novelName = req.getParameter("novel_name");
                String introduction = req.getParameter("introduction");
                String categoryIdsJson = req.getParameter("categoryIds");
                
                // 解析分类ID数组
                List<Integer> categoryIds = null;
                if (categoryIdsJson != null && !categoryIdsJson.isEmpty()) {
                    Gson gson = new Gson();
                    categoryIds = gson.fromJson(categoryIdsJson, 
                        new TypeToken<List<Integer>>(){}.getType());
                }
                
                // 处理文件上传
                String coverUrl = null;
                Part coverFilePart = req.getPart("coverFile");
                if (coverFilePart != null && coverFilePart.getSize() > 0) {
                    try {
                        // 生成唯一文件名
                        String originalFileName = coverFilePart.getSubmittedFileName();
                        String fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
                        String uniqueFileName = "novel/cover_" + System.currentTimeMillis() + fileExtension;
                        
                        // 保存临时文件
                        File tempDir = new File(TEMP_DIR);
                        if (!tempDir.exists()) {
                            tempDir.mkdirs();
                        }
                        
                        File tempFile = new File(tempDir, uniqueFileName.replace("/", "_"));
                        coverFilePart.write(tempFile.getAbsolutePath());
                        
                        // 上传到OSS
                        FileUploadOss.fileupload(uniqueFileName, tempFile.getAbsolutePath());
                        coverUrl = "https://mysteriouslamb.oss-cn-hangzhou.aliyuncs.com/" + uniqueFileName;
                        
                        // 删除临时文件
                        tempFile.delete();
                        
                    } catch (Exception e) {
                        e.printStackTrace();
                        // 文件上传失败，使用默认封面
                        coverUrl = null;
                    }
                }
                
                Map<String, Object> createResult = authorworkservice.createNovel(
                    user.getUser_id(), novelName, introduction, coverUrl, categoryIds);
                
                Gson gson = new GsonBuilder().serializeNulls().create();
                out.write(gson.toJson(createResult));
                
            } else {
                Map<String, Object> result = new HashMap<>();
                result.put("code", 404);
                result.put("msg", "请求路径不存在");
                
                Gson gson = new Gson();
                out.write(gson.toJson(result));
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("msg", "服务器内部错误: " + e.getMessage());
            
            Gson gson = new Gson();
            out.write(gson.toJson(result));
        }
    }
}
